use crate::controls::control_utils::show_messagebox;
use crate::globals::constants::*;
use std::time::Duration;
use windows::Win32::UI::WindowsAndMessaging::MB_ICONINFORMATION;
use windows_service::Result;
use windows_service::service::{ServiceAccess, ServiceState};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};

/// 停止服务
pub fn stop_service() -> Result<()> {
    // 连接到服务管理器
    let manager_access = ServiceManagerAccess::CONNECT;
    let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;

    // 打开服务
    let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP;

    // 尝试打开服务
    let service = match service_manager.open_service(SERVICE_NAME, service_access) {
        Ok(service) => service,
        Err(e) => {
            // 提取错误代码
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "停止服务 - 错误",
                &format!("无法打开服务！错误代码: {}", error_code),
                windows::Win32::UI::WindowsAndMessaging::MB_ICONWARNING,
            );
            return Err(e);
        }
    };

    // 检查服务状态
    let service_status = service.query_status()?;
    if service_status.current_state == ServiceState::Stopped {
        show_messagebox("停止服务", "服务已经处于停止状态！", MB_ICONINFORMATION);
        return Ok(());
    }

    // 停止服务
    match service.stop() {
        Ok(_) => {
            // 等待服务停止
            let mut attempts = 0;
            while service.query_status()?.current_state != ServiceState::Stopped && attempts < 10 {
                std::thread::sleep(Duration::from_secs(1));
                attempts += 1;
            }

            // 检查是否成功停止
            if service.query_status()?.current_state == ServiceState::Stopped {
                show_messagebox("停止服务", "服务已成功停止！", MB_ICONINFORMATION);
            } else {
                show_messagebox(
                    "停止服务 - 警告",
                    "服务停止命令已发送，但服务未能在预期时间内停止。",
                    windows::Win32::UI::WindowsAndMessaging::MB_ICONWARNING,
                );
            }
        }
        Err(e) => {
            // 服务停止失败
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_messagebox(
                "停止服务 - 错误",
                &format!("服务停止失败！错误代码: {}", error_code),
                windows::Win32::UI::WindowsAndMessaging::MB_ICONWARNING,
            );
            return Err(e);
        }
    }

    Ok(())
}
